package main

import (
	"bytes"
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

type IPExpires struct {
	IP         string
	ExpireTime time.Time
}

type VIPInfo struct {
	Token   string
	Expires []IPExpires
}

//# 这些用户被组织成一个列表
var gUsers []VIPInfo

func init() {
	var v VIPInfo
	v.Token = "token_duocore"
	gUsers = append(gUsers, v)
}

func registerConfig(config *gin.RouterGroup) {
	// GET http://127.0.0.1:4210/white/config?token=token_duocore
	// 将这个IP加入白名单
	config.GET("", getConfig)
}

// 请求的格式
type getConfigRequest struct {
	Token string `json:"token" form:"token"`
}

// HTTP GET 获取所有用户信息。
// curl http://127.0.0.1:4210/white/config?token=token_duocore
func getConfig(ctx *gin.Context) {

	clientIp := ctx.ClientIP()
	fmt.Printf("收到了来自%s的请求：white/config\n", clientIp)
	var req getConfigRequest
	buf := &bytes.Buffer{}
	err := ctx.ShouldBind(&req)
	if err != nil {
		fmt.Println("错误，缺少参数。")
		buf.WriteString("{\"code\":2, \"msg\":\"invalid parameter\"}")
		//respond
		contentType := "application/json"
		ctx.Data(http.StatusOK, contentType, buf.Bytes())
		return
	}

	fmt.Println(req.Token)
	if req.Token == "" {
		fmt.Println("需要传入token参数")
		buf.WriteString("{\"code\":1, \"msg\":\"invalid parameter\"}")
	} else {
		buf.WriteString("{\"code\":0, \"msg\":\"ok\"}")
		for i := 0; i < len(gUsers); i++ {
			if gUsers[i].Token == req.Token {
				// 找到了token，更新或新增一下这个IP的expire时间
				findIp := false
				for j := 0; j < len(gUsers[i].Expires); j++ {
					if clientIp == gUsers[i].Expires[j].IP {
						//找到了IP，更新这个IP的exipre时间
						gUsers[i].Expires[j].ExpireTime = time.Now().Add(time.Hour)
						fmt.Printf("找到了IP%s，更新这个IP的exipre时间为%v", clientIp, gUsers[i].Expires[j].ExpireTime.String())
						findIp = true
						break
					}
				}
				if !findIp {
					// 没找到IP，新增一条
					newEntry := IPExpires{IP: clientIp, ExpireTime: time.Now().Add(time.Hour)}
					gUsers[i].Expires = append(gUsers[i].Expires, newEntry)
					fmt.Printf("没有找到IP%s新增一条。这个IP的exipre时间是%v", clientIp, newEntry.ExpireTime.String())
				}
				break
			}
		}
	}
	//respond
	contentType := "application/json"
	ctx.Data(http.StatusOK, contentType, buf.Bytes())
}
